package cn.lutu.lutu.exception;

import cn.lutu.lutu.response.ResultVO;
import cn.lutu.lutu.response.StatusCode;
import com.alipay.api.AlipayApiException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice
@Data
public class GlobalExceptionHandler {
    public GlobalExceptionHandler() {
        System.out.println("全局异常处理器启动");
    }

//    @ExceptionHandler(RuntimeException.class)
//    public ResultVO doHandlerRuntimeException(RuntimeException r){
//        log.error("error is {}",r.getMessage());
//        return new ResultVO(0,r.getMessage(),null);
//    }
    @ExceptionHandler(BindException.class)
    public ResultVO doBindException(BindException e){
        log.warn("error is {}",e.getMessage());
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVO(StatusCode.VALIDATE_ERROR,objectError.getDefaultMessage());
    }
    /**
     * 假如用全局异常处理对象处理Controller类中出现的异常，全局异常处理对象会优先查找与Controller
     * 中相匹配的异常处理方法，假如没有，会查找对应异常的父类异常处理方法。
     * @param ex
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResultVO doHandleRuntimeException(IllegalArgumentException ex){
        log.warn("IllegalArgumentException is {}",ex.getMessage());//日志级别trace<debug<info<warn<error
        return new ResultVO(0,ex.getMessage());
    }

    /**
     * 用户名或密码错误抛出的异常
     */
    @ExceptionHandler({InternalAuthenticationServiceException.class,
            BadCredentialsException.class})
    public ResultVO handleAuthenticationException(AuthenticationException e){
        //判断当前异常是否属于用户名不存在异常
        if (e instanceof InternalAuthenticationServiceException){
            log.warn("用户名不存在!");
            return new ResultVO(StatusCode.USERNAME_ERROR);
        }
        log.warn("密码错误!");
        return new ResultVO(StatusCode.PASSWORD_ERROR);
    }

    /**
     * 无权访问时抛出的异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResultVO handleAccessDeniedException(AccessDeniedException e){
        log.warn("无权访问!");
        return new ResultVO(StatusCode.FORBIDDEN_ERROR);
    }
    /**
     * Alipay运行是抛出的异常
     * */
    @ExceptionHandler(AlipayApiException.class)
    public ResultVO doaAlipayApiException(AlipayApiException e){
        log.warn("error is {}",e.getErrMsg());
        return new ResultVO(StatusCode.VALIDATE_ERROR,e.getErrMsg());
    }


}
